import 'package:family_expense/shared/models/system_setting.dart';
import 'package:family_expense/shared/services/system_setting_service.dart';
import 'package:flutter/material.dart';

class GeneralSettingView extends StatefulWidget {
  const GeneralSettingView({super.key});

  @override
  State<GeneralSettingView> createState() => _GeneralSettingViewState();
}

class _GeneralSettingViewState extends State<GeneralSettingView> {
  SystemSetting? _systemSetting;

  @override
  void initState() {
    super.initState();

    _getSetting();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('通用'),
      ),
      body: _buildBody(),
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return ListView(
      children: [
        SwitchListTile(
          title: const Text('按两次退出程序'),
          subtitle: const Text('需要按两次返回退出程序'),
          value: _systemSetting?.generalSetting?.doublePressExit ??
              GeneralSetting.doublePressExitDefaultValue,
          onChanged: (checked) {
            if (mounted) {
              setState(() {
                _systemSetting!.generalSetting!.doublePressExit = checked;
              });
            }

            SystemSettingService.saveSetting(_systemSetting!);
          },
        ),
      ],
    );
  }

  Future<void> _getSetting() async {
    final res = await SystemSettingService.setting;

    if (mounted) {
      setState(() => _systemSetting = res);
    }
  }
}
